<?php

namespace App\Api\Controllers;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class GoodsController extends BaseController
{

    /**
     * 商品列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request)
    {
        $data = DB::table('goods_cat')
            ->leftjoin('goods', 'goods_cat.id', '=', 'goods.cat_id')
            ->leftjoin('goods_stock', 'goods_stock.goods_id', '=', 'goods.id')
            ->where([
                ['goods.status' ,1],
                ['goods_cat.status' , 1]
            ])
            ->select('goods.cat_id','goods_cat.name as cat_name','goods.id','goods.name','goods.image','goods.day_per','goods.goods_desc', 'goods_stock.leave_num')
            ->get();
        $list = [];
        $host = $request->getSchemeAndHttpHost();
        foreach ($data as $item) {
            if (!array_key_exists($item->cat_id, $list)) {
                $list[$item->cat_id] = [
                    'title'    => $item->cat_name,
                    'products' => []
                ];
            }
            $list[$item->cat_id]['products'][] = [
                'id'         => $item->id,
                'name'       => $item->name,
                'day_per'    => $item->day_per,
                'leave_num'  => $item->leave_num,
                'goods_desc' => $item->goods_desc,
                'image'      => $host . $item->image,
            ];
        }
        $list = array_values($list);
        return $this->success(200,"查询成功",$list);
    }


    /**
     * 商品详情 为前端有更好的交互体验，商品列表点击时【考虑】要不要此接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail(Request $request)
    {
        $id = $request->get("id");
        if(!$id){
            return Failed(10002, []);
        }
        $record = DB::table('goods')
            ->leftjoin('goods_stock', 'goods.id', '=', 'goods_stock.goods_id')
            ->where([
                ['goods.status' ,1],
                ['goods.id' , $id]
            ])
            ->select('goods.id','goods.name','goods.image','goods.day_per','goods.goods_desc', 'goods_stock.leave_num')
            ->first();
        if (!$record) {
            return $this->fail(402,"商品已下架或不存在");
        }
        return Success(10100, $record);
    }
}
